package com.itheima.demo5.ZengDemo5;

import java.io.*;
import java.net.Socket;
import java.util.Properties;

/**
 * @ClassName serverThread
 * @Author 16799
 * @Date 2025/9/30 11:04
 * @Version 1.0
 * @Description TODO
 **/
/*
有bug，我这样尝试密码错误的情况的时候，无返回结果，卡在这里了一样
输入登录账号：
qqq
输入登录密码：
qqqq
---------------接收服务端的响应---------------------
 */
public class serverThread extends Thread{

    private Socket socket;

    public serverThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            DataInputStream dis = new DataInputStream(socket.getInputStream());
            int type = dis.readInt();
            while (true) {
                switch (type){
                    case 1:
                        register();
                        break;
                    case 2:
                        login();
                }
            }
        } catch (Exception e) {
            System.out.println("有客户端离线: " + Thread.currentThread().getName());
        }
    }

    private void register() throws Exception {
        DataInputStream dis = new DataInputStream(socket.getInputStream());
        String loginName = dis.readUTF();
        String passWord = dis.readUTF();

        String result = "注册成功";

        if (exits(loginName)){
            result = "注册失败，已经有存在的登录名";
        }else {
            Properties properties = new Properties();
            properties.setProperty(loginName,passWord);
            properties.store(new FileWriter(server.Users_File_Path,true)," ");
        }

        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
        dos.writeUTF(result);
        dos.flush();

    }

    private boolean exits(String loginName) throws Exception {
        File file = new File(server.Users_File_Path);
        if (file.exists()){
            Properties properties = new Properties();
            properties.load(new FileReader(file));

            if (properties.containsKey(loginName)){
                return true;
            }
        }
        return false;
    }

    private void login() throws Exception {
        DataInputStream dis = new DataInputStream(socket.getInputStream());
        String loginName = dis.readUTF();
        String passWored = dis.readUTF();

        String result = "登录成功";
        File file = new File(server.Users_File_Path);
        if (file.exists()){
            Properties properties = new Properties();
            properties.load(new FileReader(file));
            String okPassWord = properties.getProperty(loginName);
            if (okPassWord == null){
                result = "登录名称错误";
            }else {
                if (!okPassWord.equals(passWored)){
                    result = "密码错误";
                }
            }
        }else {
            result = "无用户信息，请先注册";
        }

        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
        dos.writeUTF(result);
        dos.flush();
    }
}
